<?php


namespace Yon\Lib;

/**
 * Class DataArray
 * @package WeChat
 */
class Base
{
    /**
     * 正常请求网关
     * @var string
     */
    protected $gateway = '';
    protected $authUrl = '';



    public function __construct($options)
    {

        if (empty($options['appKey'])) {
            throw new \Exception("Missing Config -- [appKey] 错误");
        }
        if (empty($options['appSecret'])) {
            throw new \Exception("Missing Config -- [appSecret] 错误");
        }
        if (empty($options['tenantId'])) {
            throw new \Exception("Missing Config -- [tenantId] 错误");
        }

        if (!empty($options['cache_path'])) {
            Tools::$cache_path = $options['cache_path'];
        }
        $this->config = new DataArray($options);
        self::getGatewayAddress();
    }

    /**
     * 获取租户所在数据中心域名
     * @return mixed
     * @throws \Exception
     */
    public function getGatewayAddress(){
        $cache = $this->config->get('appKey') . '_address';
        $data = Tools::getCache($cache);
        if (!empty($data)){
            $this->gateway = $data['gatewayUrl'];
            $this->authUrl = $data['tokenUrl'];
            return $data;
        }
        $map = ['tenantId' => $this->config->get('tenantId') ];
        $options['headers'][] = "Content-Type:application/json";
        $result = Tools::json2arr(Tools::get('https://apigateway.yonyoucloud.com/open-auth/dataCenter/getGatewayAddress',$map,$options));
        if (!empty( $result['data'])){
            $this->gateway = $result['data']['gatewayUrl'];
            $this->authUrl = $result['data']['tokenUrl'];
            Tools::setCache($cache, $result['data']);
        }
        return $result['data'];
    }

    /**
     * 获取 access_token
     * @return void
     */
    public function getAccessToken(){
        $cache = $this->config->get('appKey') . '_access_token';
        $this->access_token = Tools::getCache($cache);
        if (!empty($this->access_token)){
            return $this->access_token;
        } 
        $options['headers'][] = "Content-Type:application/json";
        $map = ['appKey' => $this->config->get('appKey') ,'timestamp' => time() ];
        $map['signature'] = self::getSign($map);
        $result = Tools::json2arr(Tools::get($this->authUrl.'/open-auth/selfAppAuth/base/v1/getAccessToken',$map,$options));
        if (!empty( $result['data'])){
            $this->access_token = $result['data']['access_token'];
            Tools::setCache($cache, $this->access_token, 7000);
        }
        return  $this->access_token;
    }

    /**
     * 生成支付签名
     * @param array $signData 参与签名的数据
     * @return array
     */
    protected function getSign(array $signData,string $signingStr = ''):string
    {
        ksort($signData);
        foreach ($signData as $k => $v) $signingStr .= $k . $v;
        return base64_encode(hash_hmac('sha256', $signingStr, $this->config->get('appSecret') ,true)) ;
    }


    /**
     * 注册当前请求接口
     * @param string $url 接口地址
     * @param string $method 当前接口方法
     * @param array $arguments 请求参数
     * @return string
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    protected function registerApi(&$url)
    {
        if (empty($this->access_token)) $this->access_token = $this->getAccessToken();
        return $url = $this->gateway . str_replace('ACCESS_TOKEN', urlencode($this->access_token), $url);
    }

}